package com.qm.console.controller.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qm.console.controller.dto.BaseRsp;
import com.qm.console.controller.dto.ResultEnum;
import com.qm.console.controller.response.BaseResponse;
import com.qm.console.model.UserInfo;
import com.qm.console.service.SysUserRoleService;
import com.qm.console.service.UserInfoService;
import com.qm.console.controller.response.BaseResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Edison.hu on 18/7/25.
 */
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    //@Autowired
    //DateUtil dateUtil;

    @GetMapping
    public BaseRsp currentUserInfo() {
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        return new BaseRsp(ResultEnum.SUCCESS, activeUser.getUsername());
    }

    /**
     * 用户列表.
     * @return
     */
    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    @RequiresPermissions("userInfo:view")
    public JSONObject userInfo(
            @RequestParam(value="offset", required = false, defaultValue="0") int offset,
            @RequestParam(value="limit", required=false, defaultValue="20") int pageSize,
            @RequestParam(value="username", required=false) String username,
            @RequestParam(value="startTime", required=false) String startTime,
            @RequestParam(value="endTime", required=false) String endTime,
            @RequestParam(value="orderType", required=false, defaultValue="DESC") String orderType,
            @RequestParam(value="orderBy", required=false, defaultValue="updated_at") String orderBy
            ){
        JSONObject data = new JSONObject();
        int count = userInfoService.getUserInfoCount(username,startTime, endTime);
        data.put("count", count);
        JSONArray dataItems = new JSONArray();
        List<UserInfo> UserInfoList = userInfoService.getUserInfoList(offset,pageSize,username,startTime, endTime,orderBy,orderType);
        for(UserInfo userInfo: UserInfoList)
        {
            dataItems.add(userInfo.toJsonObject());
        }
        data.put("items", dataItems);
        BaseResponse results = new BaseResponse(data);
        return results;
    }


    /**
     * 用户添加;
     * @return
     */
    @RequestMapping(value = "/userAdd", method = RequestMethod.POST)
    //@RequiresPermissions("userInfo:add")
    public JSONObject userInfoAdd(@RequestBody JSONObject params){
        JSONObject data = new JSONObject();
        int roleId = params.getInteger("roleId");
        String password = params.getString("password");
        BaseResponse results = new BaseResponse(data);
        if (password == null)
        {
            password = "123456"; // 没有传密码的情况下
        }
        String userName = params.getString("username");
        try {
            userInfoService.addNewUser(password, userName);  // 添加用户
            UserInfo userInfo = userInfoService.findByUsername(userName);   //找到用户
            sysUserRoleService.setUserSysRole(userInfo.getUid(), roleId);  //绑定角色
        }catch (DuplicateKeyException e)
        {
            results.put("msg", "用户名已存在");
            results.put("code", -1);
        }
        catch (Exception e)
        {
            results.put("msg", e.toString());
            results.put("code", -1);
        }
        return results;
    }

    /**
     * 用户修改;
     * @return
     */
    @RequestMapping(value = "/userUpdate", method = RequestMethod.POST)
    @RequiresPermissions("userInfo:change")
    public JSONObject userInfoUpdate(@RequestBody JSONObject params){
        JSONObject data = new JSONObject();
        BaseResponse results = new BaseResponse(data);
        int uid = params.getInteger("uid");
        int role_id = params.getInteger("roleId");
        try {
            UserInfo userInfo = userInfoService.findByUid(uid);   //找到用户
            sysUserRoleService.setUserSysRole(userInfo.getUid(), role_id);  //绑定角色
        }
        catch (Exception e)
        {
            results.put("msg", e.toString());
            results.put("code", -1);
        }
        return results;

    }

    /**
     * 用户删除;
     * @return
     */
    @RequestMapping(value = "/userDel", method = RequestMethod.POST)
    @RequiresPermissions("userInfo:del")//权限管理;
    public JSONObject userDel(@RequestBody JSONObject params){
        JSONObject data = new JSONObject();
        int uid = params.getInteger("uid");
        BaseResponse results = new BaseResponse(data);
        try {
            sysUserRoleService.unBindUserSysRole(uid);  //删除绑定角色
            userInfoService.delUserByUid(uid); //删除用户自己
        }catch (Exception e)
        {
            results.put("msg", e.toString());
            results.put("code", -1);
        }
        return results;
    }


    //重置密码
    @RequestMapping(value = "/resetPassword")
    public JSONObject resetPassword(@RequestParam(value="uid", required = false, defaultValue="0") int uid){
        JSONObject data = new JSONObject();
        BaseResponse results = new BaseResponse(data);
        try {
            UserInfo userInfo = userInfoService.findByUid(uid);   //找到用户
            userInfoService.resetPassword(userInfo, "astroecho123##"); // 重置密码123456
        } catch (Exception e) {
            results.put("msg", e.toString());
            results.put("code", -1);
        }
        return results;
    }

    //修改密码
    @RequestMapping(value = "/updatePassword")
    public JSONObject UpdatePassword(@RequestBody JSONObject params){
        JSONObject data = new JSONObject();
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        String oldPassword = params.getString("oldPassword");
        String newPassword = params.getString("newPassword");
        BaseResponse results = new BaseResponse(data);
        try {
             if (!userInfoService.UpdatePassword(activeUser, oldPassword, newPassword))
             {
                 results.put("msg", "旧密码验证失败");
                 results.put("code", -1);
             }
        } catch (Exception e) {
            results.put("msg", e.toString());
            results.put("code", -1);
        }
        return results;
    }
}

